package com.kb.design.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.http.HttpException;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kb.design.common.MeException;
import com.kb.design.constant.Constants;
import com.kb.design.dto.DesignProjectDTO;
import com.kb.design.entity.*;
import com.kb.design.enums.DesignStatus;
import com.kb.design.enums.ProjectStatus;
import com.kb.design.enums.UserRole;
import com.kb.design.mapper.postgreSQL.*;
import com.kb.design.service.CustomContactService;
import com.kb.design.service.CustomUserService;
import com.kb.design.service.DesignRoleService;
import com.kb.design.service.ProjectService;
import com.kb.design.util.CommonUtil;
import com.kb.design.util.StringUtils;
import com.kb.design.vo.DesignInfoDataVO;
import com.kb.design.vo.DetailsInfoVO;
import com.kb.design.vo.ProjectListVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;


import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * (CustomUser)表服务实现类
 *
 * @author makejava
 * @since 2023-08-22 10:57:17
 */
@Service
@DS("slave-1")
public class ProjectServiceImpl implements ProjectService {
    private static final Logger log = LoggerFactory.getLogger(ProjectServiceImpl.class);

    @Resource
    private ProjectMapper projectMapper;
    @Resource
    private DesignOrderMapper designOrderMapper;
    @Resource
    private StatusTransferMapper statusTransferMapper;
    @Resource
    private DesignFileMapper designFileMapper;
    @Resource
    private DesignRequirementMapper designRequirementMapper;
    @Resource
    private CustomContactMapper customContactMapper;
    @Resource
    private CustomContactService customContactService;
    @Resource
    private DesignResponsiblePersonMapper responsiblePersonMapper;

    private CustomUserMapper userMapper;
    @Resource
    private CustomUserService userService;
    @Resource
    private DesignRoleService roleService;
    @Resource
    private DesignDeptMapper designDeptMapper;

    @Value("${ERP.deliveryUrl}")
    private String deliveryUrl;

    @Override
    public Map<String, Object> getProjectTypeCount(DesignProjectDTO designProjectDTO) {
        Map<String, Object> newHashMap = new HashMap<>();
        newHashMap.put("assigned", 0);
        newHashMap.put("myAssigned", 0);
        newHashMap.put("waitingCheck", 0);
        newHashMap.put("noDistribution", 0);
        //根据角色设置查询角色
        boolean isAdmin = false;
        DesignRole designRole = roleService.queryRoleByCode(designProjectDTO.getCreateBy());
        if (Objects.nonNull(designRole) &&
                designRole.getRoleKey().contains(UserRole.ADMIN.getKey()) || designRole.getRoleKey().contains(UserRole.CUSTOMER_SERVICE.getKey()) || designRole.getRoleKey().contains(UserRole.VALOR.getKey())) {
            designProjectDTO.setDataPermissions("all");
            isAdmin = true;
        } else {
            //todo  还得判断部门负责人
            designProjectDTO.setResponsiblePersonList(designProjectDTO.getCreateBy());
        }
        List<DesignProject> projectList = projectMapper.getProjectTypeCount(designProjectDTO);
        if (!CollectionUtils.isEmpty(projectList)) {
            newHashMap.put("assigned", projectList.size());
            //responsiblePersonId等于当前登录人
            long count = projectList.stream().filter(e -> e.getResponsiblePersonId().equals(designProjectDTO.getCreateBy())).count();
            newHashMap.put("myAssigned", count);
            //checkPersonList
            long check = 0;
            if (isAdmin) {
                check = projectList.stream().filter(e -> !e.getCheckPersonList().isEmpty()).count();
            } else {
                check = projectList.stream().filter(e -> e.getCheckPersonList().contains(Integer.valueOf(designProjectDTO.getCreateBy()))).count();
            }
            newHashMap.put("waitingCheck", check);
            //status = 10 page_leader为空 和 status = 20 且 design_leader为空的数据
            long noDistribution = 0;
            if (isAdmin) {
                noDistribution = projectList.stream().filter(e ->
                        (e.getStatus().equals(DesignStatus.ENCAPSULATION.getIndex()) && Objects.isNull(e.getPageLeader())) ||
                                (e.getStatus().equals(DesignStatus.DESIGN.getIndex()) && Objects.isNull(e.getDesignLeader()))
                ).count();
            } else if (designRole.getRoleKey().contains("page")) {
                noDistribution = projectList.stream().filter(e ->
                        (e.getStatus().equals(DesignStatus.ENCAPSULATION.getIndex()) && Objects.isNull(e.getPageLeader()))
                ).count();
            } else if (designRole.getRoleKey().contains("design")) {
                noDistribution = projectList.stream().filter(e ->
                        (e.getStatus().equals(DesignStatus.DESIGN.getIndex()) && Objects.isNull(e.getDesignLeader()))
                ).count();
            }
            newHashMap.put("noDistribution", noDistribution);
        }
        return newHashMap;
    }

    @Override
    public DesignProject queryById(Long id) {
        return null;
    }


    @Override
    public Map<String, Object> chartLegend(DesignProjectDTO designProjectDTO) {
        Map<String, Object> newHashMap = new HashMap<>();
        newHashMap.put("chartLegend", "饱和度");
        newHashMap.put("growthRate", "78");
        newHashMap.put("20", "78");

        return newHashMap;
    }

    @Override
    public List<DesignInfoDataVO> searchDesignInfoData(DesignProjectDTO designProjectDTO) {
        //查询设计记录表数据
        LambdaQueryWrapper<DesignResponsiblePerson> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(DesignResponsiblePerson::getProjectId, designProjectDTO.getProjectId())
//                .isNotNull(DesignResponsiblePerson::getCommonId)
                .lt(DesignResponsiblePerson::getNodeStatus, designProjectDTO.getDesignStatus());
        List<DesignResponsiblePerson> designResponsiblePersonList = responsiblePersonMapper.selectList(queryWrapper);

        List<DesignInfoDataVO> list = new ArrayList<>();
        for (DesignResponsiblePerson designResponsiblePerson : designResponsiblePersonList) {
            DesignInfoDataVO designInfoDataVO = new DesignInfoDataVO();
            BeanUtils.copyProperties(designResponsiblePerson, designInfoDataVO);
            designInfoDataVO.setNodeName(DesignStatus.getName(designResponsiblePerson.getNodeStatus()));
            //附件
            LambdaQueryWrapper<DesignFile> wrapper = Wrappers.lambdaQuery();
            wrapper.eq(DesignFile::getType, designResponsiblePerson.getNodeStatus()).last("limit 1");
            DesignFile designFile = designFileMapper.selectOne(wrapper);
            if (designFile != null) {
                designInfoDataVO.setUrl(designFile.getUrl());
            }
            list.add(designInfoDataVO);
        }
        return list;
    }

    @Override
    public Page<ProjectListVO> queryByPage(DesignProjectDTO projectDTO) {
        Page<DesignProjectDTO> page = new Page<>(projectDTO.getPage(), projectDTO.getPerPage());
        //数据权限 查询权限
        /**
         * 数据权限逻辑
         * 先查询当前登录人角色 当是 管理员 或者客服 或者 valor 则查询所有
         *
         *  projectDTO.setDataPermissions("all");
         *  xml那里
         *         <if test="projectDTO.responsiblePersonList != null and projectDTO.responsiblePersonList != ''">
         *             and P.relevant_responsible_person  &amp;&amp; ARRAY[${projectDTO.responsiblePersonList}]
         *         </if>
         */
        boolean isAdmin = false;
        DesignRole designRole = roleService.queryRoleByCode(projectDTO.getCreateBy());
        if (Objects.isNull(designRole) || Objects.isNull(designRole.getRoleKey())) {
            throw new MeException("当前登录人角色不存在！");
        }
        //当前登录人角色包含管理员 或者客服 或者 valor 则查询所有 contain
        if (Objects.nonNull(designRole) &&
                designRole.getRoleKey().contains(UserRole.ADMIN.getKey()) || designRole.getRoleKey().contains(UserRole.CUSTOMER_SERVICE.getKey()) || designRole.getRoleKey().contains(UserRole.VALOR.getKey())) {
            projectDTO.setDataPermissions("all");
            isAdmin = true;
        } else {
            //todo  还得判断部门负责人
            projectDTO.setResponsiblePersonList(projectDTO.getCreateBy());
        }
        //todo 根据当前登录人 查询是否是部门负责人 是 查询 部门下的人 不是就 setResponsiblePersonList为自己的工号  再加上角色 如果是admin和客服 直接不用设置权限
        if (Objects.equals(projectDTO.getTabType(), "1")) {
            projectDTO.setResponsiblePersonList(projectDTO.getCreateBy());
//            projectDTO.setResponsiblePersonList("23988,25856,25629");
        }
        if (Objects.equals(projectDTO.getTabType(), "2")) {
            projectDTO.setResponsiblePersonId(projectDTO.getCreateBy());
        }
        if (Objects.equals(projectDTO.getTabType(), "3")) {
            if (isAdmin) {
                projectDTO.setStatus(DesignStatus.CHECK.getIndex());
            } else {
                projectDTO.setCheckPersonList(projectDTO.getCreateBy());
            }
        }
        if (Objects.equals(projectDTO.getTabType(), "4")) {
            projectDTO.setNoLeader("No");
            //根据角色设置只查询对应状态数据
            if (isAdmin) {
                projectDTO.setRoleKey("admin");
            } else if (designRole.getRoleKey().contains("page")) {
                projectDTO.setRoleKey("page");
            } else if (designRole.getRoleKey().contains("design")) {
                projectDTO.setRoleKey("design");
            } else {
                projectDTO.setRoleKey("未知");
            }
        }
        return projectMapper.queryByPage(page, projectDTO);
    }

    @Override
    public Page<DesignProject> queryNoOrderProject(DesignProjectDTO projectDTO) {
        Page<DesignProject> page = new Page<>(projectDTO.getPage(), projectDTO.getPerPage());
        LambdaQueryWrapper<DesignProject> query = Wrappers.lambdaQuery();
        query.eq(StringUtils.isNotEmpty(projectDTO.getProjectName()),DesignProject::getProjectName, projectDTO.getProjectName());
        query.eq(StringUtils.isNotEmpty(projectDTO.getProjectNumber()),DesignProject::getProjectNumber, projectDTO.getProjectNumber());
        query.isNull(DesignProject::getOrderId).orderByDesc(DesignProject::getCreateTime);
        return projectMapper.selectPage(page, query);
    }

    @Override
    public Page<ProjectListVO> queryProjectByDesignLeader(DesignProjectDTO projectDTO) {
        Page<DesignProjectDTO> page = new Page<>(projectDTO.getPage(), projectDTO.getPerPage());
        return projectMapper.queryProjectByDesignLeader(page, projectDTO);
    }

    @Override
    public Page<ProjectListVO> queryBonusByPage(DesignProjectDTO projectDTO) {
        Page<DesignProjectDTO> page = new Page<>(projectDTO.getPage(), projectDTO.getPerPage());
        Page<ProjectListVO> projectListVOPage;
        DesignRole designRole = roleService.queryRoleByCode(projectDTO.getCreateBy());
        if (Objects.nonNull(designRole) &&
                designRole.getRoleKey().contains(UserRole.ADMIN.getKey()) || designRole.getRoleKey().contains(UserRole.CUSTOMER_SERVICE.getKey())) {
            projectDTO.setDataPermissions("all");
            projectListVOPage = projectMapper.queryBonusAdminByPage(page, projectDTO);
        } else {
            //todo  还得判断部门负责人
            projectDTO.setResponsiblePersonList(projectDTO.getCreateBy());
            projectListVOPage = projectMapper.queryBonusByPage(page, projectDTO);
        }
        return projectListVOPage;
    }

    @Override
    @DSTransactional
    public void insert(DesignProjectDTO projectDTO) {
        CommonUtil.webLog("ProjectServiceImpl.insert", projectDTO);

        /**
         * 修改 订单表数据
         * 1.查询订单表数据，如果存在，则修改订单表数据，不存在则新增订单表数据
         * 2.新增or修改项目表数据
         * 3.项目负责人流转表数据
         */
        LambdaQueryWrapper<DesignProject> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DesignProject::getOrderId, projectDTO.getOrderId());
        List<DesignProject> designProjectList = projectMapper.selectList(queryWrapper);

        DesignProject designProject = new DesignProject();
        BeanUtils.copyProperties(projectDTO, designProject);
        designProject.setStartDate(projectDTO.getStartDate());
        designProject.setProjectEndDate(projectDTO.getProjectEndDate());
        //封装状态
        designProject.setStatus(DesignStatus.ENCAPSULATION.getIndex());
        designProject.setProjectName(projectDTO.getProjectName());
        designProject.setResponsiblePersonId(projectDTO.getPackageCompetent());
        designProject.setResponsiblePersonName(userService.queryNickName(projectDTO.getPackageCompetent()));

        //点击启动
        if (Objects.equals("1", projectDTO.getOperationType())) {
            designProject.setStatus(DesignStatus.ENCAPSULATION.getIndex());
        }
        designProject.setProjectNumber(designRequirementMapper.getDesignNumber());
        designProject.setDesignSoftware(projectDTO.getDesignSoftware());
        designProject.setSalesArea(projectDTO.getSalesArea());
        //相关负责人数据写入 ,号拼接
        // 将 projectDTO.getPackageCompetent() 转换为数组格式
        if (projectDTO.getPackageCompetent() != null) {
            designProject.setRelevantResponsiblePerson(Collections.singletonList(Integer.valueOf(projectDTO.getPackageCompetent())));
        }
        //附件
//        DesignFile designFile = new DesignFile();
//        designFile.setType("1");
//        designFile.setUrl(projectDTO.getProcessingDocument());

        //保存
        if (CollectionUtil.isEmpty(designProjectList)) {
            designProject.setVersion(1);
            //根据类型判断页面按钮 0保存,1启动
            designProject.setProjectEndDate(projectDTO.getProjectEndDate());
            designProject.setProjectType(Constants.PROJECT_DOWN_ORDER);
            designProject.setId(null);
            projectMapper.insert(designProject);
//            designFile.setDesignId(designProject.getId());
//            designFileMapper.insert(designFile);

        } else {
            //修改
            //附件 先删 后增
            DesignProject oldDesignProject = designProjectList.get(0);
            LambdaQueryWrapper<DesignFile> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(DesignFile::getDesignId, oldDesignProject.getId());
            designFileMapper.delete(wrapper);
//            designFile.setDesignId(oldDesignProject.getId());
//            designFileMapper.insert(designFile);

            designProject.setId(oldDesignProject.getId());
            designProject.setVersion(oldDesignProject.getVersion() + 1);
            designProject.setProjectType(Constants.PROJECT_DOWN_ORDER);
//            designProject.setNodeStatus(Objects.equals(projectDTO.getStatus(), "0") ? DesignStatus.DRAFT.getIndex() : DesignStatus.ENCAPSULATION.getIndex());
            projectMapper.updateById(designProject);
        }
        //客户联系信息
        CustomContact customContact = new CustomContact();
        BeanUtil.copyProperties(projectDTO, customContact);
        customContact.setOrderId(projectDTO.getOrderId());
        customContact.setProjectId(designProject.getId());
//        customContactMapper.insert(customContact);
        customContactService.saveOrUpdate(customContact);
        //点了启动按钮
        if (Objects.equals("2", projectDTO.getOperationType())) {
            //修改订单数据状态
            DesignOrder designOrder = new DesignOrder();
            designOrder.setId(projectDTO.getOrderId());
            designOrder.setStatus(Constants.ORDER_STATUS__PROJECT);
            designOrder.setPinAmount(projectDTO.getPinAmount());
            designOrder.setLayers(projectDTO.getLayers());
            designOrderMapper.updateById(designOrder);

            //保存负责人信息到design_responsible_person表 生成一条记录表
            DesignResponsiblePerson designResponsiblePerson = new DesignResponsiblePerson();
            BeanUtils.copyProperties(projectDTO, designResponsiblePerson);
            designResponsiblePerson.setId(null);
            designResponsiblePerson.setResponsiblePersonId(projectDTO.getPackageCompetent());
            designResponsiblePerson.setResponsiblePersonName(userService.queryNickName(projectDTO.getPackageCompetent()));
            //封装节点状态
            designResponsiblePerson.setNodeStatus(DesignStatus.ENCAPSULATION.getIndex());
            //封装人员类型  主管
            designResponsiblePerson.setPersonType(Constants.PERSON_TYPE_COMPETENT);
            designResponsiblePerson.setDel(Constants.DEL_FLAG_NO).setProjectId(designProject.getId());
            designResponsiblePerson.setDeptId(projectDTO.getPageDepartments());
            DesignDept designDept = designDeptMapper.selectById(projectDTO.getPageDepartments());
            designResponsiblePerson.setDeptName(designDept.getDeptName());
            responsiblePersonMapper.insert(designResponsiblePerson);

        }

    }

    @Override
    public void addNoOrderProject(DesignProjectDTO projectDTO) {
        DesignProject project = new DesignProject();
        BeanUtil.copyProperties(projectDTO, project);
        //判断是封装还是设计 1 封装
        List<Integer> relevantResponsiblePerson = new ArrayList<>();
        if (Objects.equals(projectDTO.getIsPage(), "1")) {
            // 将 projectDTO.getPackageCompetent() 转换为数组格式
            if (projectDTO.getPackageCompetent() != null) {
                relevantResponsiblePerson.add(Integer.valueOf(projectDTO.getPackageCompetent()));
                project.setPageLeader((projectDTO.getResponsiblePersonId()));
                project.setPageDepartments(projectDTO.getPageDepartments());
            }

            project.setStatus(DesignStatus.ENCAPSULATION.getIndex());
        } else {
            // 将 projectDTO.getPackageCompetent() 转换为数组格式
            if (projectDTO.getDesignCompetent() != null) {
                relevantResponsiblePerson.add((Integer.valueOf(projectDTO.getDesignCompetent())));
                project.setDesignLeader(projectDTO.getResponsiblePersonId());
                project.setDesignDepartments(projectDTO.getDesignDepartments());
            }
            project.setStatus(DesignStatus.DESIGN.getIndex());
        }
        relevantResponsiblePerson.add((Integer.valueOf(projectDTO.getResponsiblePersonId())));
        project.setRelevantResponsiblePerson(relevantResponsiblePerson);
        String nickName = userService.queryNickName(projectDTO.getResponsiblePersonId());
        project.setProjectNumber(designRequirementMapper.getDesignNumber());
        project.setResponsiblePersonName(nickName);
        project.setResponsiblePersonId(projectDTO.getResponsiblePersonId());
        if (Objects.nonNull(projectDTO.getProjectEndDate())) {
            projectDTO.setProjectEndDate(projectDTO.getProjectEndDate());
        }
        projectMapper.insert(project);
        //生成2条数据 主管和工程师的
        for (int i = 1; i < 3; i++) {
            DesignResponsiblePerson designResponsiblePerson = new DesignResponsiblePerson();
            String responsiblePersonId;
            if (Objects.equals("1", projectDTO.getIsPage())) {
                //封装节点状态
                designResponsiblePerson.setNodeStatus(DesignStatus.ENCAPSULATION.getIndex());
                designResponsiblePerson.setDeptId(projectDTO.getPageDepartments());
                DesignDept designDept = designDeptMapper.selectById(projectDTO.getPageDepartments());
                designResponsiblePerson.setDeptName(designDept.getDeptName());
                if (i == 1) {
                    //封装人员类型  主管
                    responsiblePersonId = projectDTO.getPackageCompetent();
                } else {
                    responsiblePersonId = projectDTO.getResponsiblePersonId();
                }
            } else {
                //封装节点状态
                designResponsiblePerson.setNodeStatus(DesignStatus.DESIGN.getIndex());
                designResponsiblePerson.setDeptId(projectDTO.getDesignDepartments());
                DesignDept designDept = designDeptMapper.selectById(projectDTO.getDesignDepartments());
                designResponsiblePerson.setDeptName(designDept.getDeptName());
                if (i == 1) {
                    //封装人员类型  主管
                    responsiblePersonId = projectDTO.getDesignCompetent();
                } else {
                    responsiblePersonId = projectDTO.getResponsiblePersonId();
                }
            }
            designResponsiblePerson.setResponsiblePersonId(responsiblePersonId);
            designResponsiblePerson.setResponsiblePersonName(userService.queryNickName(responsiblePersonId));

            designResponsiblePerson.setDel(Constants.DEL_FLAG_NO).setProjectId(project.getId());
            designResponsiblePerson.setPersonType(i);
            responsiblePersonMapper.insert(designResponsiblePerson);
        }

    }

    @Override
    public void addProject(DesignProjectDTO projectDTO) {
        DesignProject designProject = new DesignProject();
        BeanUtils.copyProperties(projectDTO, designProject);

        if (Objects.nonNull(projectDTO.getOrderId())) {
            designProject.setProjectType(Constants.PROJECT_DOWN_ORDER);
//            designProject.setNodeStatus(DesignStatus.WAIT_START.getIndex());
        }
        designProject.setDesignStatus(projectDTO.getDesignStatus());
        designProject.setProjectNumber(designRequirementMapper.getDesignNumber());
//        designProject.setPersonResponsibleName(userService.queryNickName(projectDTO.getPersonResponsibleId()));
        projectMapper.insert(designProject);
        //生成设计任务数据
        if (!Objects.equals(projectDTO.getDesignStatus(), DesignStatus.STOP.getIndex())) {
            DesignRequirement designRequirement = new DesignRequirement();
            BeanUtils.copyProperties(designProject, designRequirement, "id");
            designRequirement.setProjectId(designProject.getId());
            designRequirement.setDesignStatus(designProject.getDesignStatus());
            designRequirementMapper.insert(designRequirement);

            //任务子表
            DesignResponsiblePerson designResponsiblePerson = new DesignResponsiblePerson();
            BeanUtils.copyProperties(designRequirement, designResponsiblePerson, "id");
            designResponsiblePerson.setNodeStatus(designProject.getDesignStatus());
            responsiblePersonMapper.insert(designResponsiblePerson);
        }
    }

    @Override
    public void updateOrderData(DesignProjectDTO projectDTO) {
        CommonUtil.webLog("ProjectServiceImpl.updateOrderData", projectDTO);
        DesignOrder designOrder = new DesignOrder();
        BeanUtils.copyProperties(projectDTO, designOrder);
//        designOrder.setId(projectDTO.getId());
//        designOrder.setPinAmount(projectDTO.getPinAmount());
//        designOrder.setLayers(projectDTO.getLayers());
//        if (!Objects.isNull(projectDTO.getPersonResponsibleId())){
//
//        }
        designOrderMapper.updateById(designOrder);
    }

    @Override
    public void updateProjectData(DesignProjectDTO projectDTO) {
        //修改项目状态
        DesignProject project = new DesignProject();
        project.setId(projectDTO.getProjectId());
        DesignProject designProject = projectMapper.selectById(projectDTO.getProjectId());

        project.setStatus(DesignStatus.CHECK.getIndex());
        //第一次检查时，把项目表的负责人字段数据 复制到待检查负责人字段 用于页面 检查字段做显隐 并且加入valor部门的人
        //获取valor 部门的人
        List<Integer> longs = userMapper.queryByFunction("3");
        List<Integer> relevantResponsiblePerson = designProject.getRelevantResponsiblePerson();
        //塞入valor检查的人
        relevantResponsiblePerson.addAll(longs);
        project.setCheckPersonList(relevantResponsiblePerson);
        project.setDesignStatus("");
        projectMapper.updateById(project);
    }

    /**
     * 项目页面指派设计人员
     */
    @Override
    @DSTransactional
    public void deliveryProject(DesignProject project) {
        try {
            //交付之前 项目必须已下单
            if (Objects.isNull(project.getOrderId())) {
                throw new MeException("清先绑定项目");
            }
            project.setStatus(DesignStatus.BONUS_DISTRIBUTION.getIndex());
            //交付就是设计结束 此状态表示项目设计完成
            project.setProjectStatusAuxiliary(ProjectStatus.FINISH.getIndex());
            projectMapper.updateById(project);
            DesignOrder designOrder = designOrderMapper.queryById(project.getOrderId());
            if (Objects.isNull(designOrder.getPinAmount())) {
                throw new MeException("Pin数不能为空");
            }
            BigDecimal qty = designOrder.getPinAmount();
            LocalDate warehousingTime = project.getWarehousingTime();
            String nickName = userService.queryNickName(project.getCreateBy());
            if (Objects.nonNull(project.getWarehousingTime())) {
                // 从配置中获取基础 URL
                String baseUrl = deliveryUrl;

                // 发送 GET 请求并添加参数
                String result = HttpRequest.get(baseUrl)
                        .form("ordno", designOrder.getOrderNo())
                        //                .form("ordno", "D2024060025")
                        .form("qty", qty)
                        .form("date", warehousingTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")))
                        .form("shipman", nickName)
                        .execute()
                        .body();
                // 解析 JSON 响应
                JSONObject jsonObject = JSONUtil.parseObj(result);

                int code = jsonObject.getInt("code");
                String msg = jsonObject.getStr("msg");

                //todo 测试阶段放开
                if (code != 0) {
                    // 如果失败，抛出运行时异常，由全局异常处理器捕获返回给前端
                    throw new MeException(msg);
                }
            }
        } catch (HttpException e) {
            throw new MeException("网络请求失ERP败: " + e.getMessage());
        } catch (MeException e) {
            throw new MeException("业务异常: " + e.getMessage());
        } catch (RuntimeException e) {
            log.error("内部错误: {}", e.getMessage(), e);
            throw new MeException("内部错误，请联系管理员!");
        }
    }

    @Override
    public DetailsInfoVO searchDetailsInfo(Long id) {
        DetailsInfoVO detailsInfo = new DetailsInfoVO();
        DesignProject project = projectMapper.selectById(id);
        detailsInfo.setArea(project.getSalesArea());
        detailsInfo.setProjectNumber(project.getProjectNumber());
        detailsInfo.setActualStartTime(project.getCreateTime());
        List<DesignResponsiblePerson> personList = responsiblePersonMapper.searchDetailsInfo(id);
        for (DesignResponsiblePerson designResponsiblePerson : personList) {
            //封装信息
            if (Objects.equals(designResponsiblePerson.getNodeStatus(), DesignStatus.ENCAPSULATION.getIndex())) {
                if (Objects.equals(designResponsiblePerson.getPersonType(), Constants.PERSON_TYPE_COMPETENT)) {
                    detailsInfo.setPackageCompetent(designResponsiblePerson.getResponsiblePersonName());
                } else {
                    detailsInfo.setPackageEngineers(designResponsiblePerson.getResponsiblePersonName());
                    detailsInfo.setPackageCompleteTime(designResponsiblePerson.getCompleteTime());
                }
            }
            //设计信息
            if (Objects.equals(designResponsiblePerson.getNodeStatus(), DesignStatus.ENCAPSULATION.getIndex())) {
                if (Objects.equals(designResponsiblePerson.getPersonType(), Constants.PERSON_TYPE_COMPETENT)) {
                    detailsInfo.setDesignCompetent(designResponsiblePerson.getResponsiblePersonName());
                } else {
                    detailsInfo.setDesignEngineers(designResponsiblePerson.getResponsiblePersonName());
                    detailsInfo.setDesignCompleteTime(designResponsiblePerson.getCompleteTime());
                }
            }
        }
        return detailsInfo;
    }

    @Override
    public void update(DesignProjectDTO projectDTO) {

    }

    @Override
    public void projectBindingOrder(Long projectId, Long OrderId) {
        CommonUtil.webLog2("ProjectServiceImpl.projectBindingOrder", projectId);
        //查询订单信息
        DesignOrder order = designOrderMapper.queryById(OrderId);
        //设置项目信息
        DesignProject project = new DesignProject();
        project.setId(projectId);
        project.setOrderId(OrderId);
        project.setStartDate(order.getOrderDate());
        project.setSalesArea(order.getDept2());
        project.setProjectName(order.getFileName());
        project.setPinAmount(order.getPinAmount());
        if(Objects.nonNull(order.getLayers())){
            project.setLayers(String.valueOf(order.getLayers()));
        }
        project.setCustomerCode(order.getCustomerCode());
        project.setProjectEndDate(order.getDeliveryDate());
        projectMapper.updateById(project);

        order.setStatus(2);
        designOrderMapper.updateById(order);

    }


    @Override
    public boolean deleteById(Long id) {
        return false;
    }

    @Override
    public boolean returnOrder(Long orderId, Long projectId, String returnStatus) {
        CommonUtil.webLog2("ProjectServiceImpl.returnOrder", "orderId：projectId：returnStatus："+orderId+":"+projectId+":"+returnStatus);
        DesignProject designProject = projectMapper.selectById(projectId);
        //退到上一级 封装
        if (returnStatus.equals(DesignStatus.ENCAPSULATION.getIndex())) {
            //查询项目流转封装信息
            LambdaQueryWrapper<DesignResponsiblePerson> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.eq(DesignResponsiblePerson::getProjectId, projectId).eq(DesignResponsiblePerson::getNodeStatus, DesignStatus.ENCAPSULATION.getIndex())
                    .eq(DesignResponsiblePerson::getPersonType, 1)
                    .eq(DesignResponsiblePerson::getDel, "0").last("limit 1");
            DesignResponsiblePerson designResponsiblePerson = responsiblePersonMapper.selectOne(queryWrapper);
            if (designResponsiblePerson == null) {
                throw new MeException("未找到封装信息，无法回退到封装节点，请联系管理员或直接退回至订单");
            }
            //项目信息修改
            DesignProject project = projectMapper.selectById(projectId);

            List<Integer> relevantResponsiblePerson = project.getRelevantResponsiblePerson();
            String responsiblePersonId = project.getResponsiblePersonId();
            relevantResponsiblePerson.remove(Integer.valueOf(responsiblePersonId));
            project.setRelevantResponsiblePerson(relevantResponsiblePerson);

            project.setStatus(DesignStatus.ENCAPSULATION.getIndex());
            project.setResponsiblePersonId(designResponsiblePerson.getResponsiblePersonId());
            project.setResponsiblePersonName(designResponsiblePerson.getResponsiblePersonName());
            project.setDesignLeader(null);
            project.setPageLeader(null);
            project.setDesignDepartments(null);
            project.setDesignStatus(null);
            projectMapper.updateProjectInfo(project);
            //删除项目流转记录 软删除
            LambdaQueryWrapper<DesignResponsiblePerson> wrapper = Wrappers.lambdaQuery();
            queryWrapper.eq(DesignResponsiblePerson::getProjectId, projectId).eq(DesignResponsiblePerson::getNodeStatus, DesignStatus.DESIGN.getIndex());
            DesignResponsiblePerson person = new DesignResponsiblePerson();
            person.setDel("1");
            responsiblePersonMapper.update(person, wrapper);
            //designResponsiblePerson 插入封装主管数据
            designResponsiblePerson.setCreateTime(LocalDateTime.now());
            designResponsiblePerson.setUpdateTime(LocalDateTime.now());
            designResponsiblePerson.setCompleteTime(null);
            designResponsiblePerson.setId(null);
            responsiblePersonMapper.insert(designResponsiblePerson);
        } else {
            //退回到订单 需先判断项目是否是未下单项目
            String projectType = designProject.getProjectType();
            //修改订单状态
            DesignOrder designOrder = new DesignOrder();
            designOrder.setId(orderId);
            designOrder.setStatus(1);
            designOrderMapper.updateById(designOrder);
            if (projectType.equals("1")){
                //解绑项目
                projectMapper.update(null, Wrappers.lambdaUpdate(DesignProject.class)
                        .set(DesignProject::getOrderId, null)
                        .eq(DesignProject::getId, projectId));

            }else {
                //删除 项目
                projectMapper.deleteById(projectId);
                //删除流转记录
                LambdaQueryWrapper<DesignResponsiblePerson> queryWrapper = Wrappers.lambdaQuery();
                queryWrapper.eq(DesignResponsiblePerson::getProjectId, projectId);
                responsiblePersonMapper.delete(queryWrapper);
            }

        }
        return true;
    }

    @Override
    public boolean termination(Long projectId) {
        DesignProject designProject = new DesignProject();
        designProject.setId(projectId);
        designProject.setLifeCycle(false);
        return projectMapper.updateById(designProject) > 1;
    }

    @Override
    public List<Map<String, Object>> searchTimeLine(Long searchId) {

        List<Map<String, Object>> timeLineList = new ArrayList<>();
        LambdaQueryWrapper<DesignStatusTransfer> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DesignStatusTransfer::getProjectId, searchId);
        List<DesignStatusTransfer> transferList = statusTransferMapper.selectList(queryWrapper);

        if (!CollectionUtils.isEmpty(transferList)) {
            //排序
            List<DesignStatusTransfer> sortedList = transferList.stream()
                    .sorted(Comparator.comparing(DesignStatusTransfer::getCreateTime))
                    .collect(Collectors.toList());
            //数据组装
            for (DesignStatusTransfer designStatusTransfer : sortedList) {
                Map<String, Object> map = new HashMap<>();
                map.put("title", designStatusTransfer.getTitle());
                map.put("time", designStatusTransfer.getCreateTime());
                map.put("color", designStatusTransfer.getColor());

                timeLineList.add(map);
            }

        }

        return timeLineList;
    }

    public void insertStatusTransfer(DesignStatusTransfer designStatusTransfer) {
        designStatusTransfer.setCreateTime(LocalDateTime.now());
        statusTransferMapper.insert(designStatusTransfer);
    }

    /**
     * 修改项目表的任务状态
     *
     * @param
     */
    public void updateProjectTaskStatus(String task, Long projectId, String nodeResponsiblePersonId) {
        DesignProject designProject = new DesignProject();
        designProject.setId(projectId);
        designProject.setStatus(task);
//        designProject.setNodeResponsiblePersonId(nodeResponsiblePersonId);
        projectMapper.updateById(designProject);
    }
}
